package control

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"time"

	. "gopkg.in/mgo.v2/bson"

	"git.oschina.net/antlinker/antmqtt/mqtt/srv"
	"gopkg.in/mgo.v2"
)

func init() {
	http.HandleFunc("/data/schtotal", schtotal)
}

const (
	MGO_COLL_TOTALER = "totaler"
)

type totals struct {
	Datas     []srv.DefaultTotal
	MaxCount  int
	CurPage   int
	TotalPage int
}

func schtotal(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	curPage, _ := strconv.Atoi(r.FormValue("curPage"))
	count, _ := strconv.Atoi(r.FormValue("count"))
	startdate := r.FormValue("startdate")
	enddate := r.FormValue("enddate")

	result := &totals{}
	if count == 0 {
		count = 10
	}
	if curPage <= 0 {
		curPage = 1
	}

	start := (curPage - 1) * count

	con := M{}
	timeM := M{}
	if startdate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", startdate)
		if err == nil {
			con["curtime"] = timeM
			timeM["$gte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}

	}
	if enddate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", enddate)
		if err == nil {

			con["curtime"] = timeM
			timeM["$lte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}
	}
	Tlog.Debug("查询条件:", con)
	err := GetMyMgo().ExecSync(MGO_COLL_TOTALER, func(coll *mgo.Collection) error {

		sum, _ := coll.Find(con).Count()
		result.CurPage = curPage

		if sum == 0 {
			return nil
		}
		result.MaxCount = sum
		result.TotalPage = sum / count
		if sum%count != 0 {
			result.TotalPage++
		}
		var datas = make([]srv.DefaultTotal, 0)
		err := coll.Find(con).Sort("-curtime").Skip(start).Limit(count).All(&datas)
		if err != nil {
			return err
		}
		result.Datas = datas
		return nil
	})
	if err != nil {
		io.WriteString(w, fmt.Sprintf("读取数据失败:%v", err))
	}
	data, _ := json.Marshal(result)
	io.WriteString(w, string(data))
}
